package com.family.grandapp

import android.database.Cursor
import android.os.Bundle
import android.provider.ContactsContract
import android.util.TypedValue
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.family.grandapp.databinding.ActivityMainBinding
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var myAdapter: MyAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val spacing = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10F, resources.displayMetrics)
        binding.recycler.layoutManager = GridLayoutManager(this@MainActivity, 2)
        binding.recycler.addItemDecoration(GridSpacingItemDecoration(2, spacing.toInt(), true))
        myAdapter = MyAdapter(this@MainActivity, ArrayList())
        binding.recycler.adapter = myAdapter
    }

    override fun onResume() {
        super.onResume()
        setData()
    }

    private fun setData() {
        XXPermissions.with(this).permission(Permission.CALL_PHONE, Permission.READ_CONTACTS)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        Toast.makeText(
                            this@MainActivity,
                            "获取部分权限成功，但部分权限未正常授予",
                            Toast.LENGTH_SHORT
                        ).show()
                        return
                    }
                    val contactNumbers = getContactNumbers()
                    myAdapter.setList(contactNumbers)
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    super.onDenied(permissions, doNotAskAgain)
                }
            })
    }

    private fun getContactNumbers(): ArrayList<ArrayList<String>> {
        val contactsNumberMap = ArrayList<ArrayList<String>>()
        val phoneCursor: Cursor? = contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null
        )
        if (phoneCursor != null && phoneCursor.count > 0) {
            val numberIndex =
                phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
            val nameIndex =
                phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
            val photoIndex =
                phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)
            while (phoneCursor.moveToNext()) {
                val number: String = phoneCursor.getString(numberIndex)
                val name: String = phoneCursor.getString(nameIndex)
                val uri: String? = phoneCursor.getString(photoIndex)
                //check if the map contains key or not, if not then create a new array list with number
                val objectNameNumber = ArrayList<String>()
                objectNameNumber.add(name)
                objectNameNumber.add(number)
                objectNameNumber.add(uri.toString())
//                if (uri != null) {
//                    if (uri.isNotEmpty()) {
//                        val input: InputStream =
//                            applicationContext.contentResolver.openInputStream(Uri.parse(uri))!!
//                        BitmapFactory.decodeStream(input)
//                    }
//                }
                if (!contactsNumberMap.contains(objectNameNumber)) {
                    contactsNumberMap.add(objectNameNumber)
                }
            }
            phoneCursor.close()
        }
        return contactsNumberMap
    }
}